//
//  RecordToneViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/6/9.
//

#import "RecordToneViewController.h"
#import "SeeAudio.h"
#import "AVPlayerManager.h"
#import "CustomLineView.h"
#import "UIView_extension.h"
#import "FileManager.h"
#import "MNControl.h"
#import "WGAudioPlayer.h"
#import "LocalRecordModel.h"

@interface RecordToneViewController ()<UIScrollViewDelegate, UIGestureRecognizerDelegate> {
    CGFloat duration;
    CGFloat currentTime;
    BOOL isDragging;
}
@property (weak, nonatomic) IBOutlet UIImageView *bg;
@property (weak, nonatomic) IBOutlet UIScrollView *waveScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *actionBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (nonatomic, strong) CustomLineView *line;
@property (nonatomic, strong) MNControl *slider;
@property (nonatomic, strong) WGAudioPlayer *player;

@end

@implementation RecordToneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"音调";
    [self addBackBtn];
    [((UIButton *)[self addRigthBtn:@"完成"]) addTarget:self action:@selector(donePress) forControlEvents:UIControlEventTouchUpInside];
    [self initView];
    [self.scrollView addSubview:self.slider];

    if (self.model.needSaveUrl) {
        [self seeAudio:self.model.needSaveUrl];
    } else {
        [self seeAudio:[NSURL fileURLWithPath:[[FileManager sharedManager] getLocalFilePath:self.model.fileName]]];
    }
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.player destroyPlayer];
}

- (void)donePress {
    [self loadingHUDAlert:@"正在处理"];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *recordName = dateTurnTimeNameStr([NSDate date]);
        NSString *outPath = [AVPlayerManager getTmpRecordName:[NSString stringWithFormat:@"%@.m4a", recordName]];
        [self.player renderAudioAndWriteToFile:outPath complete:^(BOOL success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hideHudAlert];
                if (self.ReloadHandle) {
                    self.ReloadHandle([NSURL fileURLWithPath:outPath], self.title);
                }
                [self goBackAction];
            });
        }];
    });
}

- (IBAction)actionPress {
    self.actionBtn.selected = !self.actionBtn.selected;
    if (!self.actionBtn.selected) {
        [self.player mbAudioPause];
    } else {
        [self.player mbAudioPlay];
    }
}

- (IBAction)resetPress {
    self.actionBtn.selected = NO;
    [self.player mbAudioPause];
    self.slider.currentIndex = 50;
    [self.player setupPitch:0];
}

- (void)seeAudio:(NSURL *)url {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.waveScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    });
    self.player = [WGAudioPlayer new];
    [self.player initMbPlayerWithFile:url];
    [self.player mbAudioSeekTime:0.0];
    __weak __typeof(self) weakSelf = self;
    self.player.playerNodeEndBlock = ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.actionBtn.selected = NO;
            [weakSelf.waveScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
            [weakSelf.player mbAudioSeekTime:0.0];
        });
    };
    self.player.playerNodeCurrentTimeAbseBlock = ^(double currentTimeEx) {
        CGFloat scale = currentTimeEx/weakSelf.player.playerNodeDuration;
        self->currentTime = currentTimeEx;
        int allMin  = (int)self->currentTime / 60;
        int allSecond  = (int)self->currentTime % 60;
        int allMillisecond  = (self->currentTime - allSecond)*100;
        NSString *aullTime = [NSString stringWithFormat:@"%.2d:%.2d.%02d",allMin,allSecond, allMillisecond];
        weakSelf.timeLabel.text = aullTime;
        CGFloat pointX = (weakSelf.waveScrollView.contentSize.width-SCREEN_WIDTH_DEVICE)*scale;
        if (pointX < weakSelf.waveScrollView.contentOffset.x) {
            pointX = weakSelf.waveScrollView.contentOffset.x;
        }
        [UIView animateWithDuration:0.1 animations:^{
            [weakSelf.waveScrollView setContentOffset:CGPointMake(pointX, 0) animated:NO];
        }];
    };
    
    AVURLAsset  *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
    self->duration = CMTimeGetSeconds(asset.duration);
    [SeeAudio renderPNGAudioPictogramLogForAsset:asset done:^(UIImage *spectrumImage,UIImage *scaleImage,NSInteger imageWidth) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHudAlert];
            [weakSelf.waveScrollView setContentSize:CGSizeMake(imageWidth, 0)];
            UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imageWidth, 280)];
            imgv.image = spectrumImage;
            [weakSelf.waveScrollView addSubview:imgv];
            UIImageView *scaleImgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 280, imageWidth, 30)];
            scaleImgv.image = scaleImage;
            [weakSelf.waveScrollView addSubview:scaleImgv];
            
        });
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    isDragging = YES;
    [self.player mbAudioPause];
    self.actionBtn.selected = NO;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    isDragging = NO;
    [self.player mbAudioSeekTime:currentTime];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self.player mbAudioSeekTime:currentTime];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.waveScrollView == scrollView) {
        currentTime = (scrollView.contentOffset.x/(scrollView.contentSize.width-SCREEN_WIDTH_DEVICE))*self.player.playerNodeDuration;
        if (currentTime > self.player.playerNodeDuration) {
            currentTime = self.player.playerNodeDuration;
        } else if (currentTime <= 0) {
            currentTime = 0;
        }
        int currentMin  = (int)currentTime / 60;
        int currentSecond  = (int)currentTime % 60;
        int millisecond = (currentTime - currentSecond)*100 - currentMin*60*100;
        NSString *currentTime1 = [NSString stringWithFormat:@"%.2d:%.2d.%02d",currentMin,currentSecond, millisecond];
        self.timeLabel.text = currentTime1;
    }
}

- (void)initView {
    [self.bg setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 280, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - (IS_iPhoneX_Top + NavBarHeight + 280))];
    [self.scrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 310, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Bottom - IS_iPhoneX_Top - NavBarHeight - 50 - 310)];
    [self.scrollView setContentSize:CGSizeMake(0, 300)];
    [self.waveScrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, 310)];
    [self.view addSubview:self.line];
}

- (CustomLineView *)line {
    if (!_line) {
        _line = [[CustomLineView alloc] initCustomView:CGRectMake((SCREEN_WIDTH_DEVICE-3)/2.0, IS_iPhoneX_Top + NavBarHeight, 3, 280)];
    }
    return _line;
}

- (MNControl *)slider {
    if (!_slider) {
        _slider = [[MNControl alloc] initWithFrame:CGRectMake(41, 215, SCREEN_WIDTH_DEVICE - 82, 40)];
        _slider.maxCount = 101;
        _slider.currentIndex = 50;
        _slider.hiddenDot = YES;
        __weak typeof(self) weakSelf = self;
        _slider.SliderHandle = ^(NSInteger index) {
            [weakSelf.player setupPitch:(index - 50)*48];
        };
    }
    return _slider;
}
@end
